#!/user/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Sjy
Description: 维修方案数字孪生试验验证模块
"""

import requests
import webbrowser
from PyQt5 import QtWidgets

from .base import BaseModule
from typing import Dict, Any
import gui.controls.envs as envs

from PyQt5.QtCore import QThread, pyqtSignal


class CheckServerThread(QThread):
    """检查服务器状态的线程"""

    finished = pyqtSignal(bool, str)  # 信号：是否成功，错误信息

    def __init__(self, url):
        super().__init__()
        self.url = url

    def run(self):
        try:
            response = requests.get(self.url, timeout=3)
            if response.status_code == 200:
                self.finished.emit(True, "")
            else:
                self.finished.emit(False, f"错误代码: {response.status_code}")
        except requests.exceptions.ConnectionError:
            self.finished.emit(False, "数字孪生模块软件未启动。")
        except requests.exceptions.Timeout:
            self.finished.emit(False, "连接超时，请检查服务是否正常运行。")
        except Exception as e:
            self.finished.emit(False, f"发生未知错误: {str(e)}")


class RepairSchemeDigitalTwinModule(BaseModule):
    """维修方案数字孪生试验验证模块"""

    def __init__(self):
        super().__init__()

    def init_category(self, ribbon: envs.Ribbonbar) -> Any:
        """初始化工具栏项
        Args:
            ribbon: 工具栏
        Returns:
            Any: 工具栏项
        """
        categoryRepairSchemeDigitalTwin = ribbon.add_category(
            "维修方案数字孪生试验验证模块"
        )
        return categoryRepairSchemeDigitalTwin

    def to_localhost(self):
        """localhost:8001/#/screen-home"""
        url = "http://localhost:8001/#/screen-home"
        APP = envs.py3d

        # 创建并启动检查服务器的线程
        self.check_thread = CheckServerThread("http://localhost:8001")
        self.check_thread.finished.connect(
            lambda success, error_msg: self._handle_server_check(
                success, error_msg, url, APP
            )
        )
        self.check_thread.start()

    def _handle_server_check(self, success, error_msg, url, APP):
        """处理服务器检查结果"""
        if success:
            # 服务器正常响应，打开浏览器
            webbrowser.open(url)
        else:
            # 显示错误信息
            QtWidgets.QMessageBox.critical(APP, "连接错误", error_msg)

    def init_dock(self, tree) -> None:
        pass
